package com.zking.easyuidemo.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lisen.mvc.framework.AbstractDispatchAction;
import org.lisen.mvc.framework.ModelDrive;
import org.lisen.mvc.util.PageBean;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zking.easyuidemo.dao.BookDao;
import com.zking.easyuidemo.model.Book;

public class BookAction extends AbstractDispatchAction implements ModelDrive {
	
	private Book book = new Book();

	@Override
	public Object getModel() {
		return book;
	}
	
	private BookDao bookDao = new BookDao();
	
	public void listBooks(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		
		List<Book> books = bookDao.listBooks(book, pageBean);
		
		Map<String, Object> data = new HashMap<>();
		data.put("total", pageBean.getTotal());
		data.put("rows", books);
		
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(resp.getOutputStream(), data);
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		System.out.println("---------ok -------------");
		
		Map<String, Object> data = new HashMap<>();
		data.put("success", true);
		
		bookDao.addBook(book);
		
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(resp.getOutputStream(), data);
		
	}
	
	public void update(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		System.out.println("---------ok -------------");
		
		bookDao.updateBook(book);
		
		Map<String, Object> data = new HashMap<>();
		data.put("success", true);
		
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(resp.getOutputStream(), data);
		
	}

}
